﻿//只读字段设置
function ReadonlyFileds(FieldObj) {
    for (var i = 0; i < FieldObj.Fields.length; i++) {
        switch (FieldObj.Fields[i].Type) {
            case "Text":
                FieldObj.Fields[i].Readonly = true;
                FieldObj.Fields[i].Required = false;
                FieldObj.Fields[i].Regexp = undefined;                   
                break;
            case "Checkbox":
                FieldObj.Fields[i].Readonly = true;
                FieldObj.Fields[i].Required = false;
                break;
            case "Date":
                FieldObj.Fields[i].Type = "Date";
                FieldObj.Fields[i].Readonly = true;
                FieldObj.Fields[i].Required = false;
                FieldObj.Fields[i].Regexp = undefined;
                break;
        }
    }    
    return FieldObj;
}
function ReadonlyCols(ColObj) {
    for (var i = 0; i < ColObj.length; i++) {
        ColObj[i].InputType = null;
        if (ColObj[i].name == "Operation") {
            ColObj[i].hide = true;
            ColObj[i - 1].width = ColObj[i - 1].width + ColObj[i].width + 12;
        }
    }
    return ColObj;
} 
//初始化方法
function InIt() {
    window.progressDialog = new ProgressDialog();
    window.infoDialog = new InfoDialog();
    window.ajaxClass = new AjaxClass();
    window.selectOption = new SelectOption();
    window.autoComplete = new AutoComplete();
    window.upLoadFile = new UpLoadFile("upLoadFile", "UploadDoc_Panel", "90MB", "FileDiv", "FileHTML", "草稿,审核,确认", "草稿,审核,确认", "草稿,审核,确认", "浏览", "获取文档", "上传文档", "修改文档", "删除文档", "下载文档", false, "window.tabClass.Show(3);", "");
    window.fieldsClass = new FieldsClass();
    window.fieldsClass.AddFields("#MasterInput", window.Fields);
    window.autoMath = new AutoMath();
    window.showHidden = new ShowHidden();
    window.comment = new Comment("TabTR3", "comment");

    if (JsonOriginal.KeyList["KeyA"] == "-1") {
        //修正标题
        $("#TitleTR .Title").text($("#TitleTR .Title").text() + " > 添加表单");
        $("#ButtonPrint").remove();
        $("#ButtonSelct").remove();
        $("#ButtonSave").remove();
        $("#ButtonSubmit").remove();
        $("#ButtonDelete").remove();
        $("#ButtonRevoked").remove();
        $("#radio2, #radio3, #radio4").attr("disabled", "disabled");
        $("#ButtonNext").button({ icons: { primary: "ui-icon-check"} }).click(NextStep);
    } else {
        //修正标题
        if (window.TitleName_FieldName != undefined && window.TitleID_FieldName != undefined) {
            $("#TitleTR .Title").text($("#TitleTR .Title").text() + " > " + JsonOriginal.Operations["浏览主表"].OperationData[0][window.TitleName_FieldName] + " ( " + JsonOriginal.Operations["浏览主表"].OperationData[0][window.TitleID_FieldName] + " )");
        } else {
            $("#TitleTR .Title").text($("#TitleTR .Title").text() + " > 处理表单");
        }
        //显示评论和文档数量
        $("#TabRadio label[for=radio4]").html($("#TabRadio label[for=radio4]").html() + "（" + (JsonOriginal.Operations["获取文档"].OperationData == null ? "0" : JsonOriginal.Operations["获取文档"].OperationData.length) + "）");
        $("#TabRadio label[for=radio3]").html($("#TabRadio label[for=radio3]").html() + "（" + (JsonOriginal.Operations["获取评论"].OperationData == null ? "0" : JsonOriginal.Operations["获取评论"].OperationData.length) + "）");
        //处理不同状态
        switch (JsonOriginal.Operations["浏览主表"].OperationData[0]["status"]) {
            case "1":
                $("#ButtonNext").remove();
                $("#ButtonRevoked").remove();
                $("#ButtonSubmit").html("提交");
                if (HasntPermission("草稿") || HasntCurrentUser(JsonOriginal.Operations["浏览主表"].OperationData[0]["personID"])) {
                    $("#ButtonSelct").attr("disabled", "disabled"); $("#ButtonSave").attr("disabled", "disabled"); $("#ButtonDelete").attr("disabled", "disabled"); $("#ButtonSubmit").attr("disabled", "disabled");
                }
                //定义按钮
                $("#ButtonSelct").button({ icons: { primary: "ui-icon-search"} }).click(function () {
                    if ($(this).find(".ui-button-text").html() == "选择产品") {
                        SetSelectList();
                    } else {
                        CloseSelectList();
                    }
                });
                $("#ButtonDelete").button({ icons: { primary: "ui-icon-close"} }).click(DeleteAction);
                break;
            case "2":
                $("#ButtonSelct").remove();
                $("#ButtonNext").remove();
                $("#ButtonDelete").remove();
                $("#ButtonSubmit").html("审核");
                if (HasntPermission("审核")) {
                    $("#ButtonSave").attr("disabled", "disabled"); $("#ButtonRevoked").attr("disabled", "disabled"); $("#ButtonSubmit").attr("disabled", "disabled");
                }
                break;
            case "3":
                $("#ButtonSelct").remove();
                $("#ButtonNext").remove();
                $("#ButtonDelete").remove();
                $("#ButtonSubmit").html("确认");
                if (HasntPermission("确认")) {
                    $("#ButtonSave").attr("disabled", "disabled"); $("#ButtonRevoked").attr("disabled", "disabled"); $("#ButtonSubmit").attr("disabled", "disabled");
                }
                break;
            case "4":
                $("#ButtonSelct").remove();
                $("#ButtonNext").remove();
                $("#ButtonSave").remove();
                $("#ButtonDelete").remove();
                $("#ButtonSubmit").remove();
                $("#ButtonRevoked").remove();
                break;
        }
        $("#DetailLine").css("display", "block");
        $("#DetailList").css("display", "block");
    }
    //定义按钮
    $("#ButtonSave").button({ icons: { primary: "ui-icon-disk"} }).click(function () { SaveAction("保存"); });
    $("#ButtonSubmit").button({ icons: { primary: "ui-icon-check"} }).click(function () { SaveAction("提交"); });
    $("#ButtonRevoked").button({ icons: { primary: "ui-icon-notice"} }).click(function () { infoDialog.OpenDialog('你确认撤销该单据？', 'Alert', function () { SaveAction("撤销"); }); });
    $("#ButtonPrint").button({ icons: { primary: "ui-icon-print"} }).click(function () { infoDialog.OpenDialog('即将推出，敬请期待！', 'Alert'); });
    $("#ButtonBack").button({ icons: { primary: "ui-icon-arrowreturnthick-1-w"} }).click(function () { window.location.href = $('#UrlBack').val(); });
    //生成产品明细
    window.resizeFlexiGridCheck = new ResizeFlexiGrid("", "#ListDetail", "#CTable .flexigrid .bDiv", ["#TitleTR", "#TabTR", "#MasterInput", "#ButtonTR", "#CTable .flexigrid .hDiv"], 4, 4, -6);
    window.flexiGridCheck = new FlexiGrid("flexiGridCheck", "ListDetail", "CheckListTD", null, null, null, window.ListDetailCols, "", "", "", null, true, null, null);
    window.resizeFlexiGridCheck.Resize("resizeFlexiGridCheck");
    //写入明细数据
    if (JsonOriginal.Operations["浏览从表"].OperationData == null) {
        window.LineNo = 1;
    } else {
        window.fieldsClass.AddListDetails("ListDetail", "浏览从表", window.ListDetailCols);
        //定义行号计数
        window.LineNo = parseInt($("#ListDetail td[abbr=line_no]:last div").text()) + 1;
    }
    //生成自动添加行
    if (window.ListDetailAuto != undefined) {
        window.fieldsClass.AddListDetail("ListDetail", window.ListDetailAuto, ["&nbsp;", "&nbsp;"]);
    }
    if (window.AutoCompletes != undefined) {
        window.autoComplete.SetAutoCompletes(window.AutoCompletes, "autoComplete");
    }
    //设置相关文档和相关评论是否显示
    if (HasntPermission("草稿,审核,确认")) {
        if (JsonOriginal.Operations["获取文档"].OperationData == null) {
            $("#radio4").attr("disabled", "disabled");
        } else if (JsonOriginal.Operations["获取文档"].OperationData.length == 0) {
            $("#radio4").attr("disabled", "disabled");
        }
    }
    //生成选项夹
    window.tabClass = new TabClass("tabClass", "TabRadio", ["radio1", "radio2", "radio3", "radio4"], ["TabTR1", "TabTR2", "TabTR3", "TabTR4"], [function (index) {
        $("#ButtonSelct").button("option", "disabled", false); 
        SetResizeHeight(index);
    }, function (index) {
        $("#ButtonSelct").button("option", "disabled", true); 
        ShowLog(index);
    }, function (index) {
        $("#ButtonSelct").button("option", "disabled", true);
        window.comment.SetComment("window.tabClass.Show(" + index + ");");
    }, function () {
        $("#ButtonSelct").button("option", "disabled", true);
        window.upLoadFile.SetFileUpdate(HasPermission("草稿,审核,确认"));
        if (HasntPermission("草稿,审核,确认")) {
            $("#FileDiv input[type=text]").removeClass("Required").attr("readonly", "readonly");
            $("#FileDiv input[type=checkbox]").attr("disabled", "disabled");
            $("#FileDiv .DeleteFile").css("visibility", "hidden");
        }
    } ]);
    //设置明细列表自动高度
    window.resizeFlexiGridCheck.Height();
    //显示于隐藏
    if (window.ShowHiddenIt != undefined) {
        window.showHidden.ShowHidden(window.ShowHiddenIt);
    }
}
//设置自动高度
function SetResizeHeight(index) {
    window.tabClass.Show(index);
    switch (index) {
        case 0:
            window.resizeFlexiGridCheck.Height();
            break;
        case 1:
            window.resizeFlexiGridLog.Height();
            break;
    }
}
//显示流程记录
function ShowLog(index) {
    if (window.flexiGridLog == undefined) {
        window.resizeFlexiGridLog = new ResizeFlexiGrid("", "#ListLog", "#LTable .flexigrid .bDiv", ["#TitleTR", "#TabTR", "#ButtonTR", "#LTable .flexigrid .hDiv"], 4, 4, -10);
        window.flexiGridLog = new FlexiGrid("flexiGridLog", "ListLog", "LogListTD", "", "", "resizeFlexiGridLog", [
            { display: '系统编号', name: 'voucher_id', width: 100, sortable: true, align: 'left', hide: false },
            { display: '用户编号', name: 'UserID', width: 160, sortable: true, align: 'left', hide: false },
            { display: '用户姓名', name: 'UserName', width: 160, sortable: true, align: 'left', hide: false },
            { display: '操作日期', name: 'transact_date', width: 160, sortable: true, align: 'left', hide: false },
            { display: '操作前状态', name: 'flow_id', width: 87, sortable: true, align: 'left', hide: false },
            { display: '操作后状态', name: 'status', width: 87, sortable: true, align: 'left', hide: false },
            { display: '操作类型', name: 'OperationType', width: 90, sortable: false, align: 'left', hide: false }
        ], "流程记录", "AutoID", "desc", "", true, null, null);
        window.resizeFlexiGridLog.Resize("resizeFlexiGridLog");
        $("#ListLog tr").each(function (index, element) {
            if ($(element).find("td[abbr=flow_id] div").text() == "1" && $(element).find("td[abbr=status] div").text() == "2") {
                $(element).find("td:last div").text("提交");
            } else if ($(element).find("td[abbr=flow_id] div").text() == "2" && $(element).find("td[abbr=status] div").text() == "3") {
                $(element).find("td:last div").text("审核");
            } else if ($(element).find("td[abbr=flow_id] div").text() == "3" && $(element).find("td[abbr=status] div").text() == "4") {
                $(element).find("td:last div").text("确认");
            } else if ($(element).find("td[abbr=flow_id] div").text() == "3" && $(element).find("td[abbr=status] div").text() == "2") {
                $(element).find("td:last div").text("撤回");
            } else if ($(element).find("td[abbr=flow_id] div").text() == "2" && $(element).find("td[abbr=status] div").text() == "1") {
                $(element).find("td:last div").text("撤回");
            }
        });
        window.tabClass.Show(index);
    } else {
        window.tabClass.Show(index);
    }
    SetResizeHeight(index);
}
//自动完成 产品明细
function SelectDetailAutoComplete(event, ui, FillTo) {
    var Value = ui.item.label.substring(1, ui.item.label.length - 1).split("], [");
    var Input = ["", window.LineNo++];                                                               
    for (var i = Input.length; i < window.ListDetailCols.length - 1; i++) { Input.push(""); }
    for (var i = 0; i < Value.length; i++) { Input[FillTo[i]] = Value[i]; }
    Input.push("Delete");
    AddDetail(window.ListDetailCols, Input);
}
//选择产品
function SelectProduct(AutoID) {
    var TR = $("#ListProduct tr td[abbr='AutoID'] div[title='" + AutoID + "']:first").parent().parent();
    var Input = ["", window.LineNo++];
    TR.find("td[abbr] div").each(function (index, element) { if (index > 0) { Input.push($(element).html()); } });
    for (var i = Input.length; i < window.ListDetailSelect.length - 1; i++) { Input.push(""); }
    Input.push("Delete");
    AddDetail(window.ListDetailSelect, Input);
    TR.find("a").css("visibility", "hidden");
}
//添加 产品明细
function AddDetail(Cols, Values) {
    window.fieldsClass.AddListDetail("ListDetail", Cols, Values, "#ListDetail tr:last");
    window.resizeFlexiGridCheck.Height();
    $('#ListDetail tr:odd').addClass('erow');
    $('#ListDetail tr:even').removeClass('erow');
}
//添加选择产品列表
function SetSelectList() {
    if (window.flexiGridSelect == undefined) {
        window.resizeFlexiGridSelect = new ResizeFlexiGrid("", "#ListProduct", "#STable .flexigrid .bDiv", ["#TitleTR", "#TabTR", "#ButtonTR", "#SelectSearchTR", "#SelectPageTR", "#STable .flexigrid .hDiv"], 4, 4, -6);
        window.flexiGridSelect = new FlexiGrid("flexiGridSelect", "ListProduct", "SelectListTD", "SelectPageTR", "SelectSearchTR", "resizeFlexiGridSelect", window.SelectDetail, "产品选择列表", "AutoID", "desc", "", true, "FPNL RC PZT PNI J F", SetSelectLink);
        window.resizeFlexiGridSelect.Resize("resizeFlexiGridSelect");
        if (window.SelectListParameters != undefined) {
            for (var i in window.SelectListParameters) {
                $("#SelectSearchTR .Search").append("<input type=\"hidden\" name=\"" + i + "\" value=\"" + $("#" + window.SelectListParameters[i]).val() + "\" />");
            }
        }
        window.flexiGridSelect.LoadData("ShowSelectList();", "", "", null, null);
    } else {
        ShowSelectList();
    }
}
//取消产品明细
function CancelDetail(line_no) {
    var TR = $("#ListDetail td[abbr=line_no] div[title=" + line_no + "]:first").parent().parent();
    if (TR.find("div:eq(0)").text() == "") {
        TR.remove();
        SetSelectLink();
        window.resizeFlexiGridCheck.Height();
    } else {
        TR.toggleClass("DeleteGridTR");
    }
}
//选择产品列表隐藏选择按钮
function SetSelectLink() {
    $("#ListProduct tr td div a").css("visibility", "visible");
    $("#ListProduct tr").each(function (index, element) {
        var Check = true;
        for (var i = 0; i < window.SelectLinkFiledNames.length; i++) {
            if ($("#ListDetail tr td[abbr='" + window.SelectLinkFiledNames[i] + "'] div[title='" + $(element).find("td[abbr='" + window.SelectLinkFiledNames[i] + "'] div").attr("title") + "']:first").size() == 0) {
                Check = false;
                break;
            }
        }
        if (Check) { $(element).find("a:last").css("visibility", "hidden"); }
    });
}
//打开选择列表
function ShowSelectList() {
    window.flexiGridCheck.HiddCols(window.ShowHiddCols);
    window.flexiGridCheck.WidthCols(window.OpenWidthCols);
    SetSelectLink();
    $('#MasterInput').css('display', 'none');
    $("#ListDetail tr:last").css("display", "none");
    $('#STableTD').css('display', 'block').removeAttr('style');
    $("#ButtonSave").button("option", "disabled", true); 
    $("#ButtonDelete").button("option", "disabled", true); 
    $("#ButtonSubmit").button("option", "disabled", true); 
    $("#ButtonBack").button("option", "disabled", true); 
    $("#ButtonPrint").button("option", "disabled", true); 
    $("#radio2, #radio3, #radio4").attr("disabled", "disabled");
    $("#TabRadio").buttonset();
    $("#TitleTR .Title").text($("#TitleTR .Title").text() + " > 选择产品");
    $('#ButtonSelct').find('.ui-button-text').html('完成选择');
    window.resizeFlexiGridCheck.heightCutSelecters = ["#TitleTR", "#TabTR", "#ButtonTR", "#CTable .flexigrid .hDiv"];
    window.resizeFlexiGridCheck.fixHeight = -10;
    window.resizeFlexiGridCheck.Height();
    window.resizeFlexiGridSelect.Height();
}
//关闭选择列表
function CloseSelectList() {
    window.flexiGridCheck.ShowCols(window.ShowHiddCols);
    window.flexiGridCheck.WidthCols(window.CloseWidthCols);
    $('#MasterInput').css('display', 'block');
    $("#ListDetail tr:last").css('display', 'block').removeAttr('style');
    $('#STableTD').css('display', 'none');
    $("#ButtonSave").button("option", "disabled", false);
    $("#ButtonDelete").button("option", "disabled", false);
    $("#ButtonSubmit").button("option", "disabled", false);
    $("#ButtonBack").button("option", "disabled", false);
    $("#ButtonPrint").button("option", "disabled", false);
    $("#radio2, #radio3, #radio4").removeAttr("disabled");
    $("#TabRadio").buttonset();
    $("#TitleTR .Title").text($("#TitleTR .Title").text().replace(/ > 选择产品/, ""));
    $('#ButtonSelct').find(".ui-button-text").html("选择产品");
    window.resizeFlexiGridCheck.heightCutSelecters = ["#TitleTR", "#TabTR", "#ButtonTR", "#MasterInput", "#CTable .flexigrid .hDiv"];
    window.resizeFlexiGridCheck.fixHeight = -6;
    window.resizeFlexiGridCheck.Height();
}
//检查输入项
function CheckForm() {
    return window.fieldsClass.CheckForm(["MasterInput", "DetailList"], window.CheckDate, "window.tabClass.Show(0); $('label[for=radio1]').click();");
}
//下一步操作
function NextStep() {
    if (CheckForm()) {
        var JsonSend = { "ActionParameters": JSON.stringify([[{ "OperationKey": "下一步", "Parameters": window.fieldsClass.FillParameters(window.NextStepParameter)}]]) };
        var URLP = ""; ;
        for (var i in JsonOriginal.GetList) {
            if (i.toLowerCase() != "status") {
                URLP += "&" + i + "=" + encodeURIComponent(JsonOriginal.GetList[i]);
            }
        }
        window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction + URLP, JsonSend, "", "window.location.href = data.ReturnData[0];", "", true, false);
    }
}
//删除操作
function DeleteAction() {
    infoDialog.OpenDialog('你确认永久删除该单据？', 'Alert', function () {
        var ActionParameters = [[{ "OperationKey": "删除草稿"}]];
        window.upLoadFile.DelFileActionObj(ActionParameters);
        var JsonSend = { "ActionParameters": JSON.stringify(ActionParameters) };
        window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "window.location.href = $('#UrlBack').val();", "", true, false);
    });
}
//获取行明细参数
function GetRowParameters(ActionParameters, element, Index) {
    if ($(element).find("td[abbr=AutoID]").size() > 0) {
        if ($(element).find("div:eq(0)").text() == "") {
            ActionParameters[Index].push({ "OperationKey": "添加草稿从表", "Parameters": window.fieldsClass.FillDetailParameters(element, window.AddDraftDetail) });
        } else if ($(element).hasClass("DeleteGridTR")) {
            ActionParameters[Index].push({ "OperationKey": "删除草稿从表", "Parameters": window.fieldsClass.FillDetailParameters(element, window.DeleteDraftDetail) });
        } else {
            switch (JsonOriginal.Operations["浏览主表"].OperationData[0]["status"]) {
                case "1":
                    ActionParameters[Index].push({ "OperationKey": "修改草稿从表", "Parameters": window.fieldsClass.FillDetailParameters(element, window.SaveDraftDetail) });
                    break;
                case "2":
                    ActionParameters[Index].push({ "OperationKey": "修改审核从表", "Parameters": window.fieldsClass.FillDetailParameters(element, window.SaveAuditDetail) });
                    break;
                case "3":
                    ActionParameters[Index].push({ "OperationKey": "修改确认从表", "Parameters": window.fieldsClass.FillDetailParameters(element, window.SaveConfirmDetail) });
                    break;
            }
        }
    }
}
//保存操作
function SaveAction(KeyPre) {
    if (CheckForm()) {
        var ActionParameters;
        var Temp;
        switch (KeyPre) {
            case "保存":
                Temp = "Save";
                break;
            case "提交":
                Temp = "Submit";
                break;
            case "撤销":
                Temp = "Cancel";
                break;
        }
        switch (JsonOriginal.Operations["浏览主表"].OperationData[0]["status"]) {
            case "1":
                ActionParameters = [[{ "OperationKey": "检查是否待提交"}], []];
                break;
            case "2":
                ActionParameters = [[{ "OperationKey": "检查是否待审核"}], []];
                break;
            case "3":
                ActionParameters = [[{ "OperationKey": "检查是否待确认"}], []];
                break;
        }
        //获取从表操作数据
        $("#ListDetail tr").each(function (index, element) {
            GetRowParameters(ActionParameters, element, 1);
        });
        //获取主表操作数据
        switch (JsonOriginal.Operations["浏览主表"].OperationData[0]["status"]) {
            case "1":
                ActionParameters[1].push({ "OperationKey": KeyPre + "草稿主表", "Parameters": window.fieldsClass.FillParameters(window[Temp + "DraftParameter"], window.Fields) });
                break;
            case "2":
                ActionParameters[1].push({ "OperationKey": KeyPre + "审核主表", "Parameters": window.fieldsClass.FillParameters(window[Temp + "AuditParameter"], window.Fields) });
                break;
            case "3":
                ActionParameters[1].push({ "OperationKey": KeyPre + "确认主表", "Parameters": window.fieldsClass.FillParameters(window[Temp + "ConfirmParameter"], window.Fields) });
                break;
        }
        //获取评论操作数据
        window.comment.SetCommentActionObj(ActionParameters);
        //获取文件操作数据
        window.upLoadFile.SetFileActionObj(ActionParameters);
        var JsonSend = { "ActionParameters": JSON.stringify(ActionParameters) };
        window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "window.location.href = $('#UrlBack').val();", "", true, false);
    };
}